<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input
          v-model="query.keyWord"
          placeholder="试卷名称"
          clearable
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-select
          clearable
          filterable
          v-model="query.gradeInfoId"
          placeholder="请选择年级"
        >
          <el-option
            v-for="item in gradeInfoList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select
          v-if="query.gradeInfoId"
          clearable
          filterable
          v-model="query.subjectId"
          placeholder="请选择科目"
        >
          <el-option
            v-for="item in subjectList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          v-if="hasPermission(['system:testPaperInfo:list'])"
          @click="searchPaper"
          type="primary"
          icon="el-icon-search"
          >查询</el-button
        >
        <el-button
          icon="el-icon-circle-plus-outline"
          type="success"
          plain
          v-if="hasPermission(['system:testPaperInfo:save'])"
          @click="addPaper"
          >新增试卷</el-button
        >
        <el-button
          v-if="hasPermission(['system:testPaperInfo:export'])"
          icon="el-icon-upload2"
          plain
          @click="exportTestPaper"
          >导出</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      :data="testPaperList"
      border
      @selection-change="handleSelectionChange"
      v-loading="loading"
      style="width: 100%"
    >
      <el-table-column type="selection" align="center" width="50">
      </el-table-column>

      <el-table-column
        prop="name"
        align="center"
        min-width="180"
        :show-overflow-tooltip="true"
        label="试卷名称"
      >
      </el-table-column>

      <el-table-column
        prop="gradeInfoName"
        align="center"
        width="120"
        label="年级"
      >
      </el-table-column>

      <el-table-column prop="mark" align="center" width="80" label="总分">
      </el-table-column>

      <el-table-column
        prop="questionNumber"
        align="center"
        width="80"
        label="试题数量"
      >
      </el-table-column>

      <el-table-column
        prop="subjectName"
        align="center"
        width="120"
        label="科目"
      >
      </el-table-column>

      <el-table-column align="center" width="100" label="考试时间">
        <template slot-scope="scope">
          <span>{{ scope.row.examTime }}分钟</span>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        :show-overflow-tooltip="true"
        width="100"
        label="状态"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.publishFlag">已发布</el-tag>
          <el-tag v-else type="danger">草稿</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="remark"
        align="center"
        :show-overflow-tooltip="true"
        width="120"
        label="备注"
      >
      </el-table-column>

      <el-table-column
        prop="createDate"
        align="center"
        width="180"
        label="创建时间"
      >
      </el-table-column>

      <el-table-column align="center" min-width="100" label="操作">
        <template slot-scope="scope">
          <el-dropdown>
            <span class="el-dropdown-link">
              操作<i class="el-icon-caret-bottom"></i>
            </span>

            <el-dropdown-menu slot="dropdown">
              <!-- <el-dropdown-item
                v-if="
                  !scope.row.publishFlag &&
                  hasPermission(['system:testPaperInfo:publish'])
                "
                @click.native="publishTestPaperInfo(scope.row)"
                icon="el-icon-s-promotion"
                >发布到考试任务</el-dropdown-item
              > -->

              <el-dropdown-item
                icon="el-icon-s-promotion"
                @click.native="openAddExamTask(scope.row)"
                >添加到考试任务</el-dropdown-item
              >

              <el-dropdown-item
                icon="el-icon-s-custom"
                @click.native="openStudentsDialog(scope.row)"
                >考生管理</el-dropdown-item
              >

              <el-dropdown-item
                v-if="scope.row.publishFlag"
                @click.native="goExamMonitor(scope.row)"
                icon="el-icon-view"
                >考试监控</el-dropdown-item
              >

              <!-- <el-dropdown-item
                @click.native="printPaper(scope.row)"
                icon="el-icon-view"
                >预览/打印</el-dropdown-item
              > -->

              <el-dropdown-item
                v-if="
                  scope.row.publishFlag &&
                  hasPermission(['system:testPaperInfo:cancel'])
                "
                @click.native="cancelTestPaperInfo(scope.row)"
                icon="el-icon-bottom"
                >撤回</el-dropdown-item
              >

              <el-dropdown-item
                v-if="hasPermission(['system:testPaperInfo:relevanceQuestion'])"
                @click.native="relevanceQuestion(scope.row)"
                icon="el-icon-tickets"
                >试题管理</el-dropdown-item
              >

              <el-dropdown-item
                v-if="
                  !scope.row.publishFlag &&
                  hasPermission(['system:testPaperInfo:update'])
                "
                @click.native="updateTestPaperInfo(scope.row)"
                icon="el-icon-edit"
                >修改</el-dropdown-item
              >

              <el-dropdown-item
                v-if="
                  !scope.row.publishFlag &&
                  hasPermission(['system:testPaperInfo:deleteById'])
                "
                @click.native="deleteById(scope.row)"
                icon="el-icon-delete"
                >删除</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      :total="totalCount"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>

    <paper-question-dialog-list
      :showFlag="questionListDialog"
      @closeDialog="closeDialog"
      @close="closeForm"
      :gradeTypeList="gradeTypeList"
      :params="queryParams"
    >
    </paper-question-dialog-list>

    <paper-form
      :showFlag="formDialog"
      @closeDialog="closeDialog"
      :formData="paperForm"
      @close="closeForm"
    >
    </paper-form>

    <!-- 试卷考生管理 -->
    <el-dialog
      width="80%"
      title="试卷--考生管理"
      :visible.sync="examPaperStuDialog"
      :close-on-click-modal="false"
    >
      <!-- 搜索 添加考生 批量删除 -->
      <el-row>
        <el-col :span="16">
          <el-form>
            <el-row>
              <el-col :span="6">
                <el-form-item>
                  <el-select
                    v-model="gradeInfoId"
                    filterable
                    clearable
                    placeholder="请选择年级"
                  >
                    <el-option
                      v-for="item in gradeInfoList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item>
                  <el-input
                    v-model="keyWordStu"
                    placeholder="输入学生名字"
                    type="text"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item>
                  <el-button type="success" icon="el-icon-search"
                    >搜索</el-button
                  >
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>

        <el-col :span="6">
          <el-button type="primary" @click="addStuVisible = true" >往试卷中添加考生</el-button>
          <el-button type="danger">批量删除</el-button>
        </el-col>
      </el-row>
      <br />

      <!-- 考场考生名单列表 -->
      <el-table :data="infoStudentList" border stripe>
        <el-table-column
          type="selection"
          align="center"
          width="50"
        ></el-table-column>

        <el-table-column
          label="姓名"
          align="center"
          prop="name"
        ></el-table-column>

        <el-table-column
          label="年级"
          align="center"
          prop="grade"
        ></el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="danger">移除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 底部 -->
      <span slot="footer">
        <el-button @click="examPaperStuDialog = false">取 消</el-button>
        <el-button type="primary">完成管理</el-button>
      </span>
    </el-dialog>



<!--学员对话框-->
    <el-dialog
      width="50%"
      title="添加考生1"
      :visible.sync="addStuVisible"
      @close="addStuListDialogClosed"
      :close-on-click-modal="false"
      append-to-body
    >
     <!--选择年级  输入考生姓名   搜索学员-->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select
            v-model="query.gradeInfoId"
            filterable
            clearable
            placeholder="请选择年级"
          >
            <el-option
              v-for="item in gradeInfoList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-col>

        <el-col :span="6">
          <el-input
            v-model="query.keyWord"
            placeholder="请输入考生姓名"
          ></el-input>
        </el-col>

        <el-button
          type="primary"
          v-if="hasPermission(['system:student:list'])"
          @click="searchStudent()"
          >搜索</el-button
        >
      </el-row>
      <br />
      
      <!-- 考场考生名单列表 -->
      <el-table :data="infoStudentList" border stripe>
        <el-table-column
          type="selection"
          align="center"
          width="50"
        ></el-table-column>

        <el-table-column
          label="姓名"
          align="center"
          prop="name"
        ></el-table-column>

        <el-table-column
          label="年级"
          align="center"
          prop="grade"
        ></el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="danger">移除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 底部 -->
      <span slot="footer">
        <el-button @click="addStuDialog = false">取 消</el-button>
        <el-button type="primary">完成管理</el-button>
      </span>

       <!-- 学员分页 -->
      <el-pagination
        background
        @size-change="AllStusizeChangeHandler"
        @current-change="AllStucurrentChangeHandler"
        :current-page="AllStucurrentPage"
        :page-sizes="[10, 10, 20, 50]"
        :page-size="AllStupageSize"
        :total="AllStutotalCount"
        layout="total, sizes, prev, pager, next, jumper"
      >
      </el-pagination>
  
    </el-dialog>
    <!-- 发布到考试任务对话框 -->
    <el-dialog
      width="30%"
      title="发布至考试任务"
      :visible.sync="addExamTaskVisible"
      :close-on-click-modal="false"
    >
      <el-select v-model="examTaskValue" placeholder="请选择考试任务">
        <el-option
          v-for="item in examTaskList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>

      <!-- 底部 -->
      <span slot="footer">
        <el-button @click="addExamTaskVisible = false">取 消</el-button>
        <el-button type="primary" @click="addIdToExamTask()">确定发布</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import paperForm from "@/components/education/paper-form";
import paperQuestionDialogList from "@/components/education/paper-question-dialog-list";
import { getGradeInfoList } from "@/api/gradeInfo";
import { getSubjectInfoList } from "@/api/subjectInfo";
import { getPaperInfoList } from "@/api/testPaperInfo";

export default {
  name: "testPaper",
  components: { paperForm, paperQuestionDialogList },
  data() {
    return {
      questionListDialog: false,
      examPaperStuDialog: false,
      testPaperList: [],
      gradeInfoList: [],
      queryParams: {
        school_type: "",
        grade_type: "",
        subject_id: "",
      },
      subjectList: [],
      query: {
        keyWord: "",
        gradeInfoId: "",
        subjectId: "",
      },
      checkedTestPaperIds: [],
      keyWord: "",
      exportLoading: null,
      formDialog: false,
      loading: true,
      currentPage: 1,
      pageSize: 10,
      questionList: [],
      totalCount: 0,
      paperForm: {
        name: "",
        gradeInfoId: "",
        schoolType: "",
        remark: "",
        subjectId: "",
        publishFlag: 0,
        sort: 0,
        examTime: null,
      },
      gradeTypeList: [],
      //考生管理对话框开关
      roomStuVisible: false,
      addExamRoomVisible: false,
      addExamTaskVisible: false,
      infoStudentList: [
        {
          name: "考生1",
          grade: "一年级",
        },
        {
          name: "李明华",
          grade: "三年级",
        },
        {
          name: "阿杰",
          grade: "大一",
        },
      ],


      //存储年级信息
      gradeInfoId: null,
      gradeInfoList: [],
      //输入学生姓名输入框
      keyWordStu: "",
      examTaskList: [],
      examTaskValue: '',
      testPaperId:0,
       //添加考生对话框开关
      addStuVisible: false,
      //当前考场的考生
      studentList: [],
      //所有学生列表(未添加进考场的考生)
      infoStudentList: [],
      input: "",
      //存储年级信息
      gradeInfoId: null,
      //年级下拉框列表
      gradeInfoList: [],
      //输入学生姓名输入框
      keyWordStu: "",
      query: {
        keyWordStu: "",
        gradeInfoId: "",
      },
      //往考场中添加考生数组
      multipleSelection: [],
      //学员分页
      AllStucurrentPage: 1,
      AllStutotalCount: 0,
      AllStupageSize: 5,
      ids: [],

    };
  },

  watch: {
    "query.gradeInfoId"(val) {
      let params = {
        gradeInfoId: val,
      };
      getSubjectInfoList(params).then((response) => {
        this.subjectList = response.data.data.dataList;
      });
    },
  },

  created() {
 
  },

  mounted() {
    this.getPaperList();
    this.getToExamTaskList();
    getGradeInfoList({}).then((response) => {
      this.gradeInfoList = response.data.data.dataList;
    });
     this.getInfoStudentList();
    getGradeInfoList({}).then((response) => {
      this.gradeInfoList = response.data.data.dataList;
    });
  },

  methods: {
    //获取考试任务名称列表
    getToExamTaskList(){
      const that = this;
      var arr = [];
      that.axios
        .get(this.$http.httpUrl(`/exam/getExamTaskList`), {
        })
        .then((response) => {
          arr = response.data.data.dataList;
          arr.forEach((value, index) => {
            this.examTaskList.push({ value: value.id, label: value.name });
          });
        })
    },
    //管理考生
    openStudentsDialog(item) {
      this.examPaperStuDialog = true
      

    },
      deleteRoom(item) {
      this.$confirm(
        "此操作将删除【" +
          item.name +
          "考场，并清空在系统中的所有数据,删除后不可恢复,是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        this.axios
          .get(
            this.$http.httpUrl(
              `/system/examRoom/deleteExamRoomById?id=` + item.id
            )
          )
          .then((response) => {
            if (response.data.code === 1) {
              this.$message.success("删除成功");
              this.getExamRoomList();
            }
          });
      });
    },
    //管理考生
    examRoomStu(item) {
      this.roomStuVisible = true;
      console.log("id:" + item.id);
    },

    //添加试卷至考试任务
    openAddExamTask(item) {
      this.addExamTaskVisible = true
      this.testPaperId = item.id
      console.log(item.id)
    },
    addIdToExamTask() {
      //选中任务的ID this.examTaskValue
      const that = this;
      var arr = [];
      that.axios
        .get(this.$http.httpUrl(`/system/testPaperInfo/addToExamTask`), {
           params: {
              id:this.testPaperId,
              examTaskId:this.examTaskValue
              }
        })
        .then((response) => {
        if(response.data.data==1){
               that.$message({
                type: "success",
                message: response.data.message,
              });
          }
        })

        this.testPaperId=0
        this.examTaskId=0
         this.addExamTaskVisible = false
      // console.log("任务ID:" + this.examTaskValue)
      // this.addExamTaskVisible = false
    },
      searchStudent(){
          console.log('提交搜索處理邏輯')
      },
    // publishTestPaperInfo(item) {
    //   var that = this;
    //   if (item.questionNumber <= 0) {
    //     that.$message({
    //       type: "warning",
    //       message: "请导入试题",
    //     });
    //     return;
    //   }

    //   this.$confirm("确定试卷【" + item.name + "】发布到考试任务?", "提示", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   }).then(() => {
    //     this.axios
    //       .get(this.$http.httpUrl(`/exam/addExamTask`), {
    //         params: {
    //           testPaperId: item.id,
    //           statu: 0,
    //         },
    //       })
    //       .then((response) => {
    //         if (response.data.code === 1) {
    //           that.$message({
    //             type: "success",
    //             message: response.data.message,
    //           });
    //         }
    //         that.addTaskVisible = false;
    //       });
    //   });
    // },

    goExamMonitor(data) {
      this.$store.commit("map/updateTestPaperInfoId", data.id);
      this.$router.push("/examMonitor");
    },

    cancelTestPaperInfo(item) {
      this.$confirm("确定撤回试卷【" + item.name + "】?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.axios
          .post(
            this.$http.httpUrl(
              "/system/testPaperInfo/cancelTestPaperInfo/" + item.id
            )
          )
          .then((response) => {
            this.$message.success(response.data.message);
            this.loading = true;
            this.getPaperList();
          });
      });
    },

    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.loading = true;
      this.getPaperList();
    },

    handleSelectionChange(val) {
      this.checkedTestPaperIds = val;
      console.log(val);
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.loading = true;
      this.getPaperList();
    },

    // 点击Dialog 右上角关闭图标时触发
    closeDialog() {
      this.closeForm();
      this.loading = true;
      this.getPaperList();
    },

    searchPaper() {
      this.currentPage = 1;
      this.loading = true;
      this.getPaperList();
    },

    // 试卷导出
    exportTestPaper() {
      let that = this;
      if (that.checkedTestPaperIds.length === 0) {
        that.$message.error("请选择试卷导出");
        return;
      }
      let ids = [];
      let subjectNames = [];
      that.checkedTestPaperIds.forEach((testPaperId) => {
        ids.push(testPaperId.id);
        subjectNames.push(testPaperId.subject_name);
      });
      let params = {
        testPaperIds: ids,
        subjectNames: subjectNames,
      };
      that.exportLoading = that.$loading({
        lock: true,
        text: "正在导出试卷试题,请等待。。。",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      that.axios
        .post(that.$http.httpUrl("/system/testPaper/export"), params)
        .then(function (response) {
          if (response.data.code === 1) {
            that.$message({
              type: "success",
              message: "导出成功",
            });
            that.exportLoading.close();
            setTimeout(function () {
              location.href =
                that.$http.getFileHost() + "/" + response.data.message;
            }, 500);
          } else {
            that.$message({
              type: "error",
              message: response.data.message,
            });
          }
        });
    },

    updateTestPaperInfo(item) {
      this.formDialog = true;
      this.paperForm = {
        id: item.id,
        name: item.name,
        gradeInfoId: item.gradeInfoId,
        schoolType: item.schoolType,
        remark: item.remark,
        subjectId: item.subjectId,
        publishFlag: item.publishFlag ? 1 : 0,
        sort: item.sort,
        examTime: item.examTime,
      };
    },

    // 点击Dialog 取消按钮时触发
    closeForm() {
      this.formDialog = false;
      this.questionListDialog = false;
      this.loading = true;
      this.getPaperList();
      this.clearFormData();
    },

    deleteById(item) {
      let that = this;
      that
        .$confirm("确定删除试卷" + item.name + "?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(function () {
          that.axios
            .delete(that.$http.httpUrl("/system/testPaperInfo/" + item.id))
            .then(function (response) {
              if (response.data.code === 1) {
                that.$message({
                  type: "success",
                  message: response.data.message,
                });
                that.loading = true;
                that.getPaperList();
              } else {
                that.$message({
                  type: "error",
                  message: response.data.message,
                });
              }
            });
        });
    },

    clearFormData() {
      this.paperForm = {
        name: "",
        gradeInfoId: "",
        schoolType: "",
        remark: "",
        subjectId: "",
        publishFlag: 0,
        sort: 0,
        examTime: null,
      };
    },

    relevanceQuestion(item) {
      this.queryParams = {
        id: item.id,
        schoolType: item.schoolType,
        subjectId: item.subjectId,
        gradeInfoId: item.gradeInfoId,
        publishFlag: item.publishFlag,
      };
      this.questionListDialog = true;
    },

    addPaper() {
      this.formDialog = true;
    },

    getPaperList() {
      let params = {
        pageNumber: this.currentPage,
        pageSize: this.pageSize,
        name: this.query.keyWord,
        subjectId: this.query.subjectId,
        gradeInfoId: this.query.gradeInfoId,
      };

      getPaperInfoList(params).then((response) => {
        this.loading = false;
        this.testPaperList = response.data.data.dataList;
        console.log(response.data.data.dataList);
        this.totalCount = response.data.data.total;
      });
    },



    //学员对话框关闭事件
    addStuListDialogClosed() {
      this.query = "";
      this.getInfoStudentList();
    },
    //获取学员列表
    getInfoStudentList() {
      this.axios
        .get(this.$http.httpUrl("/system/student"), {
          params: {
            pageNumber: this.AllStucurrentPage,
            pageSize: this.AllStupageSize,
            name: this.query.keyWord,
            gradeInfoId: this.query.gradeInfoId,
          },
        })
        .then((response) => {
          this.infoStudentList = response.data.data.dataList;
          this.AllStutotalCount = response.data.data.total;
        });
    },
    //添加考生
    getStuToRoom() {
      this.multipleSelection.forEach((number, index) => {
        this.ids.push(number.id);
        console.log("Index: " + index + " Value: " + number.id);
      });
      console.log(this.ids);
      this.$message.success("添加成功");
      this.addStuVisible = false;
    },
    handleSelectionChange(val) {
      console.log(val);
      this.multipleSelection = val;
    },
    //获取学员列表
    getInfoStudentList() {
      this.axios
        .get(this.$http.httpUrl("/system/student"), {
          params: {
            pageNumber: this.AllStucurrentPage,
            pageSize: this.AllStupageSize,
            name: this.query.keyWord,
            gradeInfoId: this.query.gradeInfoId,
          },
        })
        .then((response) => {
          this.infoStudentList = response.data.data.dataList;
          this.AllStutotalCount = response.data.data.total;
        });

    },
     //学员对话框关闭事件
    addStuListDialogClosed() {
      this.query = "";
      this.getInfoStudentList();
    },
    //学员分页
    AllStusizeChangeHandler(val) {
      this.AllStupageSize = val;
      this.AllStucurrentPage = 1;
      this.getInfoStudentList();
    },
    AllStucurrentChangeHandler(val) {
      this.AllStucurrentPage = val;
      this.getInfoStudentList();
    },
    //搜索学员
    searchStudent() {
      this.currentPage = 1;
      this.getInfoStudentList();
    },
  },

  filters: {},
};
</script>
